package com.project.easyt.common.db.common.core.spring;

import  com.project.easy.common.util.exception.print.PrintException;
import  com.project.easy.common.util.string.StringUtil;
import com.project.easyt.common.db.common.core.spring.annotation.ChooseDb;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/9/7 22:05
 * @description:
 */
@Aspect
@Component
public class DataSourceAspect {
    /**
     * 环绕通知
     * @param point 切入点
     * @return 返回结果
     * @throws Throwable 异常
     */
    @Around("@annotation(com.project.easyt.common.db.common.core.spring.annotation.ChooseDb)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        ChooseDb chooseDb = method.getAnnotation(ChooseDb.class);
        if (!Objects.isNull(chooseDb)) {
            String value = chooseDb.value();
            if (StringUtil.isNotBlank(value)) {
                DynamicContextHolder.setDbType(value);
            }
            if (StringUtil.isBlank(value) && Objects.isNull(chooseDb.dbEnumValue())) {
                DynamicContextHolder.setDbType(chooseDb.dbEnumValue().getCode());
            }
        }
        try {
            return point.proceed();
        } catch (Exception e) {
            PrintException.print(e);
            return null;
        } finally {
            DynamicContextHolder.remove();
        }
        }
 }
